package com.xinggq.gateway.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关应用名过滤器
 * 为所有通过网关的请求添加应用名标识
 * 
 * @author xinggq
 * @since 1.0.0
 */
@Component
public class GatewayAppNameFilter implements GlobalFilter, Ordered {

    @Value("${spring.application.name:box-gateway}")
    private String applicationName;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header("X-Gateway-App-Name", applicationName)
                .header("X-Gateway-Timestamp", String.valueOf(System.currentTimeMillis()))
                .header("X-Gateway-Request-Id", generateRequestId())
                .build();

        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return -1; // 确保在其他过滤器之前执行
    }

    /**
     * 生成请求ID
     */
    private String generateRequestId() {
        return applicationName + "-" + System.currentTimeMillis() + "-" + 
               Thread.currentThread().getId();
    }
}